<script setup>
import api from './api'
import XEUtils from 'xe-utils'

const props = defineProps({
  url: { type: String, default: '' },
  options: { type: Object, default: () => ({}) },
  data: { type: Object, default: () => ({}) },
  child: { type: [Array, Function], default: () => [] },
})
const total = ref({})

const update = (data) => {
  if (props.url) {
    api.total(props.url, data).then(res => {
      total.value = res.data
    })
  }
}
watch(
  () => props.data,
  (val) => {
    total.value = val
  }
)
const getValue = val => {
  const {child} = props
  if(!val) 0
  if(child && XEUtils.isFunction(child)) {
    return child(val)
  } else if (child && XEUtils.isObject(val)) {
    return child.map(d => `${d.title}: ${val[d.key]}`).join(' ')
  }
  return val
}

defineExpose({ update })
</script>

<template>
  <div class="flex gap-x-3 gap-y-1 text-gray-500 flex-wrap">
    <div v-for="(d, i) in options" :key="i" class="flex items-center gap-1">
      <span class="inline-block w-2 h-2 bg-blue-500 rounded-md"></span>
      <span class="v-text-title">{{ d.title }}:</span> <span class="v-text-content">{{ getValue(total[d.key]) || 0 }}</span>
    </div>
  </div>
</template>